#include <STC15F2K60S2.H>
#include "nixie.h"
#include "latch.h"
#include "timer.h"
#include "kbd.h"
#include "ds18b20.h"
#include "Delay.h"
#include "i2c.h"

unsigned char Keynumber = 0,led = 0xff;
unsigned int T = 0;
static unsigned char T_t = 25;

void show(void)
{
	static unsigned int count_t = 99;
	static float t = 0.0;
	unsigned char mode = 0,da_mode = 0;
	if(da_mode)
		led = 0xfc;
	if(!da_mode)
		led = 0xfd;
	while(mode == 0)
	{
		Keynumber = key_return();
	count_t++;
	if(count_t == 100)
		{
			t = readt();
			T = (unsigned int)(t * 100);
			count_t = 0;
		}
		if(count_t == 0)
			t_convert();
			nixieshow(1,mode+1);
			nixieshow(5,T/1000);
			nixieshow(6,(T/100%10)+10);
			nixieshow(7,T/10%10);
			nixieshow(8,T%10);
		if(Keynumber == 13)
		{
			mode++;
			break;
		}
		if(Keynumber == 9)
		{
			switch(da_mode)
			{
				case 0: da_mode++;break;
				case 1: da_mode--;break;
			}
		}
		switch(da_mode)
		{
			case 0: T>=T_t ? da_write(255) : da_write(0);led &= 0xfe;latch(LED,led);break;
			case 1: T<=20 ? da_write(51) : (T>=40 ? da_write(204) : da_write((unsigned int)(3/20.0*T)));led &= 0xff;latch(LED,led);break;
		}
	}
	if(da_mode)
		led = 0xfa;
	if(!da_mode)
		led = 0xfb;
	while(mode == 1)
	{
		Keynumber = key_return();
		nixieshow(1,mode+1);
		nixieshow(7,T_t/10);
		nixieshow(8,T_t%10);
		if(Keynumber == 13)
		{
			mode++;
			break;
		}
		if(Keynumber == 14)
		if(T_t >=0)
			T_t--;
		if(Keynumber == 15)
			T_t++;
		if(Keynumber == 9)
		{
			switch(da_mode)
			{
				case 0: da_mode++;break;
				case 1: da_mode--;break;
			}
		}
		switch(da_mode)
		{
			case 0: T>=T_t ? da_write(255) : da_write(0);led &= 0xfe;latch(LED,led);break;
			case 1: T<=20 ? da_write(51) : (T>=40 ? da_write(204) : da_write((unsigned int)(3/20.0*T)));led &= 0xff;latch(LED,led);break;
		}
	}
	if(da_mode)
		led = 0xf6;
	if(!da_mode)
		led = 0xf7;
	while(mode == 2)
	{
		led = 0xf7;
		Keynumber = key_return();
		nixieshow(1,mode+1);
		if(Keynumber == 13)
		{
			mode = 0;
			break;
		}
		if(Keynumber == 9)
		{
			switch(da_mode)
			{
				case 0: da_mode++;break;
				case 1: da_mode--;break;
			}
		}
		switch(da_mode)
		{
			case 0: T>=T_t ? da_write(255) : da_write(0);led &= 0xfe;latch(LED,led);break;
			case 1: T<=20 ? da_write(51) : (T>=40 ? da_write(204) : da_write((unsigned int)(3/20.0*T)));led &= 0xff;latch(LED,led);break;
		}
	}
}

void main()
{
	latch(LED,0xaa);
	latch(RELAY,0x00);
	t_convert();
	Delay(1000);
	Timer2Init();
	while(1)
	{
		show();
	}
}

void timer2() interrupt 12 using 1
{
	static unsigned char count = 0;
	T2L = 0x90;		//设置定时初值
	T2H = 0xE8;		//设置定时初值
	if(++count == 6)
	{
	key_loop();
		count = 0;
	}
	
}